<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Corplist;
use App\Models\Shortstatistic;
use App\Models\Shortgroup;
use App\Models\Users;
use App\Models\Usersprofile;
use App\Models\Corpuser;
use App\Models\Corpstatistic;
use App\Models\Applylist;
use App\Services\OutputService;
use App\Services\CommonService;
use App\Services\MemberService;
use App\Services\MiniappService;
use App\Services\DwzService;
use Exception,Log;

class CorpController extends Controller
{
    public function corpList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $corpLists = Corplist::getCorpList($request->openid);
        return OutputService::success("SUCCESS",["corpLists"=>$corpLists]);
    }

    public function corpAdd(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->name)) return OutputService::error("请输入名称!");
        if (empty($request->collect)) return OutputService::error("请选择登记信息!");
        if (mb_strlen($request->name) > 35) return OutputService::error("名称不能超过35个字!");
        $collect = json_decode($request->collect);
        if (empty($collect)) return OutputService::error("请选择登记信息!");
        if (!empty($request->appid)) {
            $accessToken = MiniappService::getAccessToken($request->appid);
            if ($accessToken["status"] == "error") return OutputService::error("接口失败！");
            $checkResult = MiniappService::msgSecCheck($accessToken["access_token"],$request->name.$request->address,$request->openid);
            if (!$checkResult) return OutputService::error("输入的内容存在违规!");
        }
        $memberParamas = MemberService::userMemberParamas($request->openid);
        $corp_id = md5(time().rand(10000,99999));
        $avatar = empty($request->avatar) ? "" : $request->avatar;
        $notice = empty($request->notice) ? "" : $request->notice;
        Corplist::corpListCreate($request->openid,$corp_id,$request->name,$avatar,$request->collect,$request->examine,$request->notice,$memberParamas["end_time"]);
        return OutputService::success("SUCCESS",["corp_id"=>$corp_id]);
    }

    public function corpUpdate(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->name)) return OutputService::error("请输入名称!");
        if (empty($request->collect)) return OutputService::error("请选择登记信息!");
        if (mb_strlen($request->name) > 35) return OutputService::error("名称不能超过35个字!");
        $collect = json_decode($request->collect);
        if (empty($collect)) return OutputService::error("请选择登记信息!");
        if (!empty($request->appid)) {
            $accessToken = MiniappService::getAccessToken($request->appid);
            if ($accessToken["status"] == "error") return OutputService::error("接口失败！");
            $checkResult = MiniappService::msgSecCheck($accessToken["access_token"],$request->name.$request->address,$request->openid);
            if (!$checkResult) return OutputService::error("输入的内容存在违规!");
        }
        $avatar = empty($request->avatar) ? "" : $request->avatar;
        $notice = empty($request->notice) ? "" : $request->notice;
        Corplist::corpListUpdate($request->openid,$request->corp_id,$request->name,$avatar,$request->collect,$request->examine,$notice);
        return OutputService::success("SUCCESS");
    }

    public function corpDetial(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("单位不存在!");
        $corpUserCount = Corpuser::corpUserCount($request->corp_id);
        return OutputService::success("SUCCESS",["corpList"=>$corpList,"corpUserCount"=>$corpUserCount]);
    }

    public function corpSample(Request $request)
    {
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListSample($request->corp_id);
        if (empty($corpList)) return OutputService::error("单位不存在!");
        return OutputService::success("SUCCESS",["corpList"=>$corpList]);
    }

    public function corpUserJoin(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $record_id = md5($request->openid.time().rand(1000,9999));
        $day = date("Ymd",time());
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("单位不存在!");
        $status = ($corpList->examine == 1) ? 2 : 4;
        $corpUser = Corpuser::corpUserDetial($request->openid,$request->corp_id);
        $phone = empty($request->phone) ? "" : $request->phone;
        $license = empty($request->license) ? "" : $request->license;
        $idcard = empty($request->idcard) ? "" : $request->idcard;
        $student_id = empty($request->student_id) ? "" : $request->student_id;
        $employee_id = empty($request->employee_id) ? "" : $request->employee_id;
        $remark = empty($request->remark) ? "" : $request->remark;
        $avatar = empty($request->avatar) ? "" : $request->avatar;
        try {
            if (empty($corpUser)) {
                Corpuser::corpUserAdd($request->openid,$request->corp_id,$request->name,$phone,$license,$idcard,$student_id,$employee_id,$remark,$avatar,$status);
            } else {
                Corpuser::corpUserUpdate($request->openid,$request->corp_id,$request->name,$phone,$license,$idcard,$student_id,$employee_id,$remark,$avatar,$status);
            }
        } catch (Exception $e) {
            return OutputService::error("加入失败,请检查信息是否正确!");
        }
        $userProfile = Usersprofile::usersProfileExist($request->openid);
        if (empty($userProfile)) {
            Usersprofile::usersProfileAdd($request->openid,$request->name,$phone,$license,$idcard,$avatar);
        } else {
            Usersprofile::usersProfileUpdate($request->openid,$request->name,$phone,$license,$idcard,$avatar);
        }
        return OutputService::success("SUCCESS",["record_id"=>$record_id]);
    }

    public function corpUserList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("单位不存在!");
        $corpUserLists = Corpuser::corpUserList($request->corp_id);
        return OutputService::success("SUCCESS",["corpUserLists"=>$corpUserLists]);
    }

    public function corpUser(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $corpUser = Corpuser::corpUserDetial($request->openid,$request->corp_id);
        $applyListCount = Applylist::applyCount($request->corp_id,$request->openid);
        $corpUser->apply = $applyListCount;
        return OutputService::success("SUCCESS",["corpUser"=>$corpUser]);
    }

    public function applyListCheck(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $applyLists = Applylist::applyListCheck($request->corp_id);
        return OutputService::success("SUCCESS",["applyLists"=>$applyLists]);
    }

    public function userCheck(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("申请不存在!");
        Corpuser::corpUserStatus($request->uopenid,$request->corp_id,$request->status,$request->status_msg);
        return OutputService::success("审核状态更新成功");
    }

    public function applyList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("申请不存在!");
        $applyLists = Applylist::applyList($request->corp_id,$request->day,$request->status);
        return OutputService::success("SUCCESS",["applyLists"=>$applyLists]);
    }

    public function applyResult(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->apply_id)) {
            $lastApplyList = Applylist::userLastApplyList($request->openid);
            if (empty($lastApplyList)) return OutputService::error("当前暂无申请记录!");
            $id = $lastApplyList->id;
        } else {
            $id = $request->apply_id;
        }
        $applyResult = Applylist::applyResult($request->openid,$id);
        return OutputService::success("SUCCESS",["applyResult"=>$applyResult]);
    }

    public function applyDetial(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $applyDetial = Applylist::applyDetial($request->corp_id,$request->id);
        $corpUser = Corpuser::corpUserDetial($applyDetial->openid,$request->corp_id);
        $applyDetial->avatar = $corpUser->avatar;
        $applyDetial->name = $corpUser->name;
        return OutputService::success("SUCCESS",["applyDetial"=>$applyDetial]);
    }

    public function corpStatistic(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        $corpList = Corplist::corpListDetial($request->openid,$request->corp_id);
        if (empty($corpList)) return OutputService::error("社区不存在!");
        $start_time = date("Ymd",strtotime($request->start_day));
        $end_time = date("Ymd",strtotime($request->start_end));
        $corpStatistics = Corpstatistic::getCorpStatistic($request->corp_id,[$start_time,$end_time]);
        return OutputService::success("SUCCESS",["corpStatistics"=>$corpStatistics]);
    }

    public function corpDel(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        Corplist::corpListDel($request->openid,$request->corp_id);
        return OutputService::success("SUCCESS");
    }

    public function corpApply(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        $image = empty($request->imgage) ? "" : $request->imgage;
        if (empty($request->apply_id)) {
            $apply_id = Applylist::applyAdd($request->openid,$request->corp_id,$request->type,$request->reason,strtotime($request->time_start),strtotime($request->time_end),$image,date("Ymd",time()));
        } else {
            $apply_id = $request->apply_id;
            Applylist::applyUpdate($apply_id,$request->openid,$request->corp_id,$request->type,$request->reason,strtotime($request->time_start),strtotime($request->time_end),$image);
        }
        return OutputService::success("申请提交成功",["apply_id"=>$apply_id]);
    }

    public function corpApplyLast(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        $lastApply = Applylist::corpLastApply($request->corp_id,$request->openid);
        return OutputService::success("SUCCESS",["lastApply"=>$lastApply]);
    }

    public function applyStatus(Request $request)
    {
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        if (empty($request->apply_id)) return OutputService::error("参数错误!");
        Applylist::applyListStatus($request->apply_id,$request->corp_id,$request->status,$request->status_msg);
        return OutputService::success("SUCCESS");
    }

    public function shortStatic(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("参数错误!");
        $phase_start = str_replace("-", "",$request->start);
        $phase_end = str_replace("-", "",$request->end);
        $shortStatistics = Shortstatistic::shortStatistic($request->short_id,$phase_start,$phase_end);
        $dateLists = CommonService::getDateFromRange($request->start,$request->end,"Ymd");
        $statistics = [];
        foreach ($dateLists as $dateList) {
            $phase = str_replace("-", "", $dateList);
            $shortStatistic = $shortStatistics->where("phase",$phase)->first();
            if (empty($shortStatistic)) {
                $statistics[] = ["uv"=>0,"pv"=>0,"phase"=>$dateList];
            } else {
                $statistics[] = ["uv"=>$shortStatistic->uv,"pv"=>$shortStatistic->pv,"phase"=>$dateList];
            }
        }
        return OutputService::success("SUCCESS",["statistics"=>$statistics]);
    }

    public function recordStatic(Request $request)
    {
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $sign = md5($request->short_id."sk".$request->key);
        if ($sign != $request->sign) return OutputService::error("参数错误!");
        $record_id = $request->record_id;
        $short_id = $request->short_id;
        $code = empty($request->code) ? "" : $request->code;
        $short = Cache::get('short_'.$short_id);
        if (empty($short)) {
            $short = Shortlist::shortListDetial($short_id);
            if (empty($short)) return OutputService::error("短链接不存在或已删除!");
            Cache::put('short_'.$short_id,$short,3600);
        }
        $time = time();
        $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        Redis::hincrby('short_uv_'.date("Ymd",time()),$short_id,1);
        $siteRecord = new Shortrecord(["tbnum"=>$record_id[0]]);
        $siteRecord->creatShortRecord($record_id,$short_id,$code,$request->system,$request->browser,$request->device,$ip);
        return OutputService::success("SUCCESS",["short"=>$short]);
    }
}